import router, { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import View from '@/components/View'
import { $utils } from '@/utils/common'
import { getMyInfo } from '@/api'
import { qiankunActions } from '@/qiankun/globalState'
const { deepCopy, titleCase, uuid } = $utils

const routes = [
  {
    name: '机构管理',
    path: '/org',
    type: 0,
    componentName: '',
    icon: 'clipboard',
    children: [
      {
        name: '部门管理',
        path: '/deplist', //二级路径名称
        type: 1, // 1==菜单
        componentName: 'dept/index', // 组件路径
        hidden: false,
        icon: 'clipboard',
        children: null
        // modules: "enterprise",
      },
      //
      {
        name: '角色管理',
        path: '/roleList',
        type: 1,
        componentName: 'role/index',
        hidden: false,
        icon: 'clipboard',
        children: null
      },
      {
        name: '人员管理',
        path: '/personList',
        type: 1,
        componentName: 'person/index',
        hidden: false,
        icon: 'clipboard',
        children: null
      },
      {
        name: '基础信息',
        path: '/base',
        type: 1,
        componentName: 'base/index',
        hidden: false,
        icon: 'clipboard',
        children: null
      }
    ]
  },
  {
    name: '告警消息',
    path: '/warning',
    type: 0,
    hidden: false,
    componentName: '',
    icon: 'clipboard',
    children: [
      {
        name: '告警消息',
        path: '/list',
        type: 1,
        hidden: false,
        componentName: 'warning/index',
        icon: 'clipboard',
        children: []
      },
      {
        name: '告警详情',
        path: '/detail',
        type: 1,
        hidden: true,
        componentName: 'warning/detail',
        icon: 'clipboard'
      }
    ]
  }
]

const permission = {
  namespaced: true,
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    permissionCode: [] // 权限按钮
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
    // 存储按钮权限
    SET_BTN: (state, data) => {
      state.permissionCode = data
    }
  },
  actions: {
    // 生成路由  监管不要modules
    GenerateRoutes({ commit, rootGetters, dispatch }, val) {
      return new Promise((resolve, reject) => {
        getMyInfo()
          .then(res => {
            console.log('🤡 ~ res:-( ', res)
            // 用户信息 权限菜单
            const {
              // sysPermissionList: allList,
              sysUser: {
                id,
                userName,
                realName,
                avatar,
                sex,
                deptName,
                roleName,
                tenantId,
                mobile,
              },
              sysHeadMenuList,
              roleList
            } = res.result
            let allList = sysHeadMenuList[val ? val.index : (sessionStorage.getItem('activeIndex') || 0)].sysPermissionList
            commit(
              'user/SET_USERINFO',
              {
                id,
                userName: realName,
                avatar,
                sex,
                deptName,
                roleName,
                mobile,
                roleList,
                tenantId,
                sysHeadMenuList
              },
              {
                root: true
              }
            )
            // const allList = routes;
            handle(allList)
            console.log(allList, subRoutes)

            const sdata = deepCopy(allList)
            const rdata = deepCopy(allList)
            const zdata = deepCopy(allList)

            const sidebarRoutes = filterAsyncRouter(sdata, false, 0)
            const rewriteRoutes = filterAsyncRouter(rdata, false, 1)
            const addRoutes = filterAsyncRouter(zdata, false, 2)

            // 存储权限按钮标识符
            commit('user/SET_PERMISSIONS', permissionBtnList, {
              root: true
            })
            commit('SET_ROUTES', rewriteRoutes)
            commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
            commit('SET_TOPBAR_ROUTES', sidebarRoutes)
            commit('SET_DEFAULT_ROUTES', sidebarRoutes)
            // 处理子路由的
            const childRoutes = [
              {
                path: '/modules',
                name: 'Modules',
                component: Layout,
                hidden: true,
                children: Object.keys(subRoutes)
                  .reduce((c, item) => {
                    c.push(
                      ...subRoutes[item].map(i => ({
                        ...i,
                        path: `${i.meta.modules}${i.path}`,
                        component: View
                      }))
                    )

                    return c
                  }, [])
                  .concat({
                    path: '*',
                    name: 'ModulesAll',
                    component: View
                  })
              }
            ]
            console.log('GenerateRoutes', childRoutes)
            router.addRoutes([
              ...addRoutes,
              ...childRoutes,
              {
                path: '*',
                redirect: '/404',
                hidden: true
              }
            ])
            console.log('🏆 ~ router:', router)
            commit('SET_BTN', permissionBtnList)
            // 向子应用下发权限路由数据
            qiankunActions.setGlobalState({
              routers: subRoutes,
              userInfo: {
                userName,
                avatar,
                sex,
                deptName,
                roleName,
                roleList,
                id
              },
              permissionCode: permissionBtnList
            })
            router.options.isAddDynamicMenuRoutes = true
            resolve()
          })
          .catch(err => {
            console.log(err)
            router.options.isAddDynamicMenuRoutes = false
            reject()
          })
      })
    }
  }
}
// 权限按钮
const permissionBtnList = []
// 子菜单路由
const subRoutes = {}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = 0) {
  return asyncRouterMap.filter(route => {
    // 处理按钮
    if (route.type === 2) {
      return false
    }
    if (
      type === 2 &&
      route.type === 1 &&
      route.component !== 'ParentView' &&
      route.meta.modules !== 'main'
    ) {
      return false
    }
    if (type === 1 && route.children) {
      route.children = filterChildren(route.children)
    }
    if (type === 2 && route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.meta.modules === 'main') {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach(el => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

function handle(target, path, name) {
  target.forEach((item, index) => {
    if (item.type === 2) {
      permissionBtnList.push(item.permissionCode)
      return false
    }
    const data = {}
    data.hidden = item.hidden
    data.type = item.type
    if (item.type === 0) {
      data.component = 'Layout'
      data.path = item.path
      name = [item.name]
      data.redirect = 'noRedirect'
    } else if (item.type === 1) {
      data.path = item.path ? item.path.replace(/\//, '') : ''
      if (item.children && item.children.length && !item.componentName) {
        data.component = 'ParentView'
        name = name.concat(item.name)
      } else {
        data.component = item.componentName
      }
    }
    data.meta = {
      title: item.name || '--',
      icon: item.icon || 'icon-star',
      noCache: false,
      link: null,
      modules: item.modules || 'main',
      parent: name,
      keepAlive: item.keepAlive,
      componentName: item.componentName
    }
    data.name = titleCase(
      (item.componentName
        ? item.componentName.replace(/\//g, '')
        : 'Component') + uuid()
    )
    data.subPath = `${!path || path === 'null' ? '' : path}${item.path}`
    // 处理应用路由
    if (
      data.type === 1 &&
      data.component !== 'ParentView' &&
      data.meta.modules !== 'main'
    ) {
      if (!subRoutes[data.meta.modules]) subRoutes[data.meta.modules] = []
      subRoutes[data.meta.modules].push({
        name: data.name,
        path: data.subPath,
        component: data.component,
        meta: data.meta,
        hidden: false,
        parent: name

        // data.hidden, // TODO 测试微服务都设置false
      })
    }
    target[index] = {
      ...data,
      ...(Array.isArray(item.children) && item.children.length > 0
        ? {
            children: item.children
          }
        : '')
    }

    if (item.children) {
      handle(item.children, data.subPath, name)
      // target[index].children = item.children.filter(
      //   (i) => i.type !== 2
      // );
    }
  })
}
export const loadView = view => {
  // 路由懒加载
  return () => Promise.resolve(require(`@/views/modules/${view}.vue`).default)
}

export default permission
